package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 添加购物车
     * 分析redis中购物车数据结构
     * redis中一共有五种结果：string， hash， list， set， zSet
     * 购物车存储选hash结构存储
     * 具体结构为：{key, {hashKey, hashValue}}
     * 其中key为：userId
     *     hashKey为：skuId
     *     hashValue为：sku对象
     */
    public void saveCart(Cart cart) {
        //得到当前用户在redis中存放的购物车的key
        String key = LyConstants.CART_PRE+UserHolder.getUserId();
        //得到当前key对应的hash
        BoundHashOperations<String, String, String> cartHash = redisTemplate.boundHashOps(key);
        //得到当前新添加的购物车对象hashKey
        String hashKey = cart.getSkuId().toString();
        //判断当前hashKey是否有对应的购物车对对象hashValue
        Boolean hasKey = cartHash.hasKey(hashKey);
        if(hasKey){
            //得到原来购物车中hashKey对应的购物车对象
            String oldCartStr = cartHash.get(hashKey);
            //将字符串格式的购物车转成对象
            Cart oldCart = JsonUtils.toBean(oldCartStr, Cart.class);
            //合并购物车数量
            cart.setNum(cart.getNum()+oldCart.getNum());
        }
        //保存购物车
        cartHash.put(hashKey, JsonUtils.toString(cart));
    }

    public List<Cart> findCarts() {
        //得到当前用户在redis中存放的购物车的key
        String key = LyConstants.CART_PRE+UserHolder.getUserId();
        //得到当前key对应的hash
        BoundHashOperations<String, String, String> cartHash = redisTemplate.boundHashOps(key);
        //判断对应的购物车数据是否存在
        if(cartHash==null || cartHash.size()==0){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //得到购物车列表
        List<Cart> carts = cartHash.values()
                .stream()
                .map(cartStr -> JsonUtils.toBean(cartStr, Cart.class))
                .collect(Collectors.toList());
        return carts;
    }

    public void saveCarts(List<Cart> carts) {
        carts.forEach(cart -> {
            saveCart(cart);
        });
    }

    public void delCart(Long userId) {
        //得到当前用户在redis中存放的购物车的key
        String key = LyConstants.CART_PRE+userId;
        //redisTemplate.opsForHash().delete(key);
        //redisTemplate.boundHashOps(key).delete("27359021563");

        redisTemplate.delete(key);

    }
}
